package club.easin.common;

import club.easin.MYException;
import club.easin.enums.Exenum;
import club.easin.pow.dto.PwUser;
import club.easin.pow.dto.UserSession;
import club.easin.utils.Base64;
import club.easin.utils.CheckUtils;
import club.easin.utils.redis.RedisUntil;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

@Service("UserBl")
public class UserBl {

    @Autowired
    private RedisUntil redisUntil;

    public UserSession verifyToken(HttpServletRequest request){
        String token=request.getParameter("token");
        UserSession userSession=new UserSession();
        userSession.setToken(token);
        String userid=null;
        if(CheckUtils.isNull(token)) throw new MYException(Exenum.LOGIN_AGAIN);
        try {
            userid=new String(Base64.decode(token));
        }catch (Exception e){
            e.printStackTrace();
            throw new MYException(Exenum.SYS_ERROE);
        }
        String userstring=(String) redisUntil.get(userid);
        PwUser user= JSON.parseObject(userstring,PwUser.class);
        if(user==null) throw new MYException(Exenum.LOGIN_AGAIN);
        userSession.setUser(user);
        return userSession;


    }
}
